from fastapi import APIRouter,Request,Response, responses
from fastapi.responses import JSONResponse
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
from app.plugins.RsaEncrypt import decrypt_data
from app.plugins.AesEncrypt import AESencrypt
from app.plugins.SHA1 import sha1_encrypt
from app.plugins.CheckJWT import create_token
import json
from redis.asyncio import Redis
import os,sys
BASE_DIR = os.path.dirname(os.path.realpath(sys.argv[0]))
path = os.path.join(BASE_DIR, 'app/templates')
templates = Jinja2Templates(directory=path)

class login(BaseModel):
    account: str
    password: str
login_router = APIRouter()
@login_router.get("/login")
def get_login(request:Request):
    return templates.TemplateResponse("login.html", {"request": request})
@login_router.get("/login/publickey")
def get_publickey(request:Request):
    # 获取公钥,避免每次公钥都是这个，对公钥进行aes加密
    t = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC43IyaUKumw59Dtz0bJfWqkzjMJOkxJNwMc2QTKF4LqUS7rUnaJQXTUkynL4KcM6f20HcAVckOd4FBuw3UcetCjCQu1J1SWUYxGvLwFD+yrbj/XOqQ8M3h3hX8/CS74EzwifvXB/c/EJ/pDCeWQZhcRzKNyu5Nox1Qo/dk8bKZ6wIDAQAB'
    public_key=AESencrypt(t)
    return JSONResponse({"public_key": public_key},status_code=200)
@login_router.post("/logincheck")
async def post_login(request:Request,data:login):
    #解密
    password = decrypt_data(data.password)
    password = sha1_encrypt(password)
    async with Redis.from_url(url="redis://localhost:6379/0",decode_responses=True) as redis:
        userinfo = await redis.smembers('userinfo')
        userinfo = [json.loads(item) for item in list(userinfo)]
        for item in userinfo:
            if item['name'] == data.account and item['password'] == password:
                data_uname = {"username":data.account}
                token = create_token(data_uname)
                responses = JSONResponse({"msg": "登录成功"},status_code=200)
                responses.set_cookie(key="Authorization",value=token)
                responses.set_cookie(key="username",value=data.account)
                return responses
        return Response(status_code=401, content="账号、密码错误，请重新输入")